<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/11 0011
 * Time: 上午 10:25
 */

namespace App\Http\Classes;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

class Admin
{
    private $tableName = 'admins';
    private $tableDB = null;
    private $error = 0;
    private $message = array(
        0 => '修改密码失败',
        1 => '获取信息失败',
        2 => '令牌过期',
        3 => '帐号与密码不匹配'
    );

    public function __construct( $id = null )
    {
        $this->tableDB = DB::table( $this->tableName );

        if ( $id !== null )
        {
            $this->tableDB = $this->tableDB->where('id', '=', $id);
        }
    }

    public function login( $account, $password )
    {
        $token = $this->createToken();
        $admin = $this->tableDB->where('account', '=', $account)->where('password', '=', hash('md5', $password));
        if ( $admin->update(['token' => $token]) )
        {
            return $admin->get()[0];
        }
        else
        {
            $this->error = 3;
            return null;
        }
    }

    public function logout()
    {
        Session::forget('ADMIN_INFO', $admin);
    }

    public function loginByCookie( $token )
    {
        $result = $this->tableDB->where('token', '=', $token)->get();
        if ( $result )
        {
            return $result[0];
        }
        else
        {
            $this->error = 2;
            return false;
        }
    }

    public function tokenVerify( $token )
    {
        $result = $this->tableDB->where('token', '=', $token)->count();
        if ( $result == 1 )
        {
            return true;
        }
        else
        {
            $this->error = 2;
            return false;
        }
    }

    public function getMessage()
    {
        return $this->message[ $this->error ];
    }

    private function createToken()
    {
        $token = Common::getRand();
        return hash('md5', $token);
    }
}